package com.secsbrain.cmdb.component;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.secsbrain.cmdb.biz.utils.command.CommandExecutor;
import com.secsbrain.cmdb.biz.utils.command.ExecuteStrategy;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * Created by yangyang.zhang on 2017/7/3.
 */
@Component
public class CommandRunner {
    @Value("${command.run.server.hostname:}")
    private String remoteHost;
    @Value("${command.run.max.timeout:600000}")
    private long maxTimeout;
    @Value("${command.is.remote:false}")
    private boolean isRemote;
    private String sshCommand;
    private CommandExecutor commandExecutor;

    @PostConstruct
    public void init() {
        if (isRemote && StringUtils.isBlank(remoteHost)) {
            throw new IllegalArgumentException("缺少必要配置项command.run.server.hostname");
        }
        sshCommand = "ssh " + remoteHost;
        this.commandExecutor = new CommandExecutor(this.maxTimeout);
    }

    /**
     * 调用命令，按行读取返回结果，并调取相应回调函数
     *
     * @param command  命令内容
     * @param callback 处理数据的回调
     * @throws IOException
     * @see ExecuteStrategy
     */

    public void exec(String command, ExecuteStrategy callback) throws IOException {
        if (isRemote) {
            commandExecutor.execSync(sshCommand, "\""+command+"\"", callback);
        } else {
            commandExecutor.execSync(command, null, callback);
        }

    }
}
